package com.example.demo.leetcode.top100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _9找到字符串中所有字母异位词
 * @description
 * @date 2023/06/04 21:39
 * <p>
 * ******************************************************
 */
public class _9找到字符串中所有字母异位词 {

    public List<Integer> findAnagrams(String s, String p) {
        Map<Character, Integer> windows = new HashMap<>();
        Map<Character, Integer> needs = new HashMap<>();

        // 需要查找的字符串的字典
        for (char c : p.toCharArray()) {
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }

        // 双指针划分窗口
        int left = 0, right = 0;
        // 符合字符个数
        int valid = 0;
        // 记录结果
        List<Integer> res = new ArrayList<>();

        while (right < s.length()) {
            char c = s.charAt(right);
            right++;

            if (needs.containsKey(c)) {
                windows.put(c, windows.getOrDefault(c, 0) + 1);
                if (windows.get(c).equals(needs.get(c))) {
                    valid++;
                }
            }

            // 判断左侧窗口是否要收缩
            while (right - left >= p.length()) {
                if (valid == needs.size()) {
                    res.add(left);
                }

                char d = s.charAt(left);
                left++;

                if (needs.containsKey(d)) {
                    if (needs.get(d).equals(windows.get(d))) {
                        valid--;
                    }
                    windows.put(d, windows.getOrDefault(d, 0) - 1);
                }
            }
        }
        return res;
    }

}
